<?php
class ModelWpPage extends Model {
	
	public function getMyPages($customer_id,$pageNum,$pageSize){
		$sql = "select a.read,b.ID,b.post_title,SUBSTRING(b.post_content,1,100)  as abstraction,IFNULL(b.post_modified,b.post_date) post_modified,b.image as thumb from customer_message a join wp_posts b on a.post_id = b.ID
				where a.customer_id =  {$customer_id} and avail_time < CURRENT_TIMESTAMP order by b.post_modified desc";
				
		if (isset($pageNum) || isset($pageSize)) {
			if ($pageNum< 0) {
				$pageNum = 0;
			}

			if ($pageSize < 1) {
				$pageSize = 20;
			}
			
			$sql .= " LIMIT " . (int)($pageNum*$pageSize) . "," . (int)$pageSize;
		}

		
		
		$query = $this->db->query($sql);

		return $query->rows;
	}


	public function unReadCount($customer_id){
        $sql = "select count(*) count from customer_message where `read` = 0 and customer_id={$customer_id} and avail_time < CURRENT_TIMESTAMP";

        $query = $this->db->query($sql);

        $c1 = $query->row['count'];

        $sql = "select count(*) count from wp_comments where `is_read` = 0 and comment_type={$customer_id}";

        $query = $this->db->query($sql);

        $c2 = $query->row['count'];

        return $c1+$c2;
    }

	
	public function getPage($customer_id,$page_id){
		$this->db->query("update wp_posts set view_count = view_count+1 where ID={$page_id} and post_type='page'");
		
		$this->db->query("update customer_message set `read` = 1,read_time=CURRENT_TIMESTAMP where post_id={$page_id} and customer_id={$customer_id} and read_time is null");
		
		$sql = "select * from wp_posts where ID =  {$page_id} and post_type='message' ";
		
		$query = $this->db->query($sql);

		$data = $query->rows;
		
		if(count($data)){
            $data[0]['comments'] = $this->getComments($page_id,$customer_id);
			return $data[0];
		}
		else
			return '';
	}
	
	public function getUserList(){
		
		$sql = "select customer_id,firstName,telephone,0 as chosen from customer order by customer_id";
		
		$query = $this->db->query($sql);

		$data = $query->rows;
		
	
		
		return $data;
		
	}

    public function getComments($post_id,$customer_id){
        $sql = "select a.*,b.image from wp_comments a left join customer b on a.user_id = b.customer_id where a.comment_post_ID =  {$post_id} and (a.user_id = {$customer_id} or a.comment_parent={$customer_id} )";


        $query = $this->db->query($sql);

        return $query->rows;

    }

    public function comment($post_id,$message,$sender_id,$sender_name){
        $sql = "insert into wp_comments 
		set comment_post_ID={$post_id},
		comment_author='{$sender_name}',
		comment_date=CURRENT_TIMESTAMP,
		comment_date_gmt=CURRENT_TIMESTAMP, 
		comment_approved=1,
		comment_parent=0,
		user_id={$sender_id},
		comment_content='{$message}'";


        $query = $this->db->query($sql);


    }
}